package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.OrderEntity;
import com.example.HaiDLaobackend.entity.OrderItemEntity;
import com.example.HaiDLaobackend.entity.ProductEntity;
import com.example.HaiDLaobackend.entity.RefundRequestEntity;
import com.example.HaiDLaobackend.service.OrderItemService;
import com.example.HaiDLaobackend.service.OrderService;
import com.example.HaiDLaobackend.service.ProductService;
import com.example.HaiDLaobackend.service.RefundRequestService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/refunds")
public class RefundController {

    private final RefundRequestService refundRequestService;
    private final OrderService orderService;
    private final OrderItemService orderItemService;
    private final ProductService productService;

    public RefundController(RefundRequestService refundRequestService,
                            OrderService orderService,
                            OrderItemService orderItemService,
                            ProductService productService) {
        this.refundRequestService = refundRequestService;
        this.orderService = orderService;
        this.orderItemService = orderItemService;
        this.productService = productService;
    }

    @GetMapping
    public ApiResponse<List<Map<String, Object>>> list(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) {
            return ApiResponse.error(401, "未登录");
        }
        List<RefundRequestEntity> list = refundRequestService.list(new LambdaQueryWrapper<RefundRequestEntity>()
                .eq(RefundRequestEntity::getUserId, currentUserId)
                .orderByDesc(RefundRequestEntity::getId));
        List<Map<String, Object>> result = new ArrayList<>();
        for (RefundRequestEntity rr : list) {
            Map<String, Object> dto = buildRefundDto(rr);
            if (dto != null) {
                result.add(dto);
            }
        }
        return ApiResponse.ok(result);
    }

    public static class RefundCreate {
        public Long orderId;
        public Long orderItemId;
        public String reason;
        public Long getOrderId() { return orderId; }
        public void setOrderId(Long orderId) { this.orderId = orderId; }
        public Long getOrderItemId() { return orderItemId; }
        public void setOrderItemId(Long orderItemId) { this.orderItemId = orderItemId; }
        public String getReason() { return reason; }
        public void setReason(String reason) { this.reason = reason; }
    }

    @PostMapping
    public ApiResponse<?> create(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                 @RequestBody RefundCreate body) {
        if (currentUserId == null) {
            return ApiResponse.error(401, "未登录");
        }
        if (body == null || body.getOrderId() == null) {
            return ApiResponse.error(400, "参数不完整");
        }
        RefundRequestEntity rr = new RefundRequestEntity();
        rr.setOrderId(body.getOrderId());
        rr.setOrderItemId(body.getOrderItemId());
        rr.setUserId(currentUserId);
        rr.setReason(body.getReason());
        rr.setStatus("PENDING");
        refundRequestService.save(rr);
        return ApiResponse.ok(buildRefundDto(rr));
    }

    @GetMapping("/{id}")
    public ApiResponse<Map<String, Object>> detail(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                                   @PathVariable Long id) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        RefundRequestEntity rr = refundRequestService.getOne(new LambdaQueryWrapper<RefundRequestEntity>()
                .eq(RefundRequestEntity::getId, id)
                .eq(RefundRequestEntity::getUserId, currentUserId));
        if (rr == null) return ApiResponse.error(404, "售后单不存在");
        Map<String, Object> dto = buildRefundDto(rr);
        return ApiResponse.ok(dto);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> remove(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                       @PathVariable Long id) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        RefundRequestEntity rr = refundRequestService.getOne(new LambdaQueryWrapper<RefundRequestEntity>()
                .eq(RefundRequestEntity::getId, id)
                .eq(RefundRequestEntity::getUserId, currentUserId));
        if (rr == null) return ApiResponse.error(404, "售后单不存在");
        // 仅允许删除已完成或已拒绝的售后单，处理中/通过中不可删除
        if (!"COMPLETED".equals(rr.getStatus()) && !"REJECTED".equals(rr.getStatus())) {
            return ApiResponse.error(400, "售后处理中或未完成，无法删除");
        }
        boolean removed = refundRequestService.removeById(id);
        return ApiResponse.ok(true);
    }

    private Map<String, Object> buildRefundDto(RefundRequestEntity rr) {
        OrderEntity order = orderService.getById(rr.getOrderId());
        if (order == null) return null;
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", rr.getId());
        dto.put("status", rr.getStatus());
        dto.put("reason", rr.getReason());
        dto.put("createdAt", rr.getCreatedAt());

        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("id", order.getId());
        orderMap.put("merchantName", order.getMerchantName());
        orderMap.put("totalAmount", order.getTotalAmount());
        orderMap.put("originalAmount", order.getOriginalAmount() != null ? order.getOriginalAmount() : order.getTotalAmount());
        orderMap.put("discountAmount", order.getDiscountAmount() != null ? order.getDiscountAmount() : java.math.BigDecimal.ZERO);
        dto.put("order", orderMap);

        OrderItemEntity item = null;
        if (rr.getOrderItemId() != null) {
            item = orderItemService.getById(rr.getOrderItemId());
        }
        if (item == null) {
            List<OrderItemEntity> items = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>()
                    .eq(OrderItemEntity::getOrderId, order.getId())
                    .last("LIMIT 1"));
            if (!items.isEmpty()) item = items.get(0);
        }
        if (item != null) {
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("id", item.getId());
            itemMap.put("title", item.getTitle());
            itemMap.put("price", item.getPrice());
            itemMap.put("quantity", item.getQuantity());
            String cover = item.getCoverImage();
            if ((cover == null || cover.isEmpty()) && item.getProductId() != null) {
                ProductEntity product = productService.getById(item.getProductId());
                if (product != null) cover = product.getCoverImage();
            }
            itemMap.put("coverImage", cover);
            dto.put("item", itemMap);
        }
        return dto;
    }
}


